<?php
/**
 * --------------------------------------------------------------
 * 栏目控制器
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\admin\model\Column as ColumnModel;
use app\admin\model\DataModel as DataModelModel;
use util\tree;

class Column extends AdminBase
{
    /**
     * 栏目列表
     */
    public function index()
    {
        $map  = $this->getSimpleSearchMap();
        $list = ColumnModel::where($map['where'])
                ->order('id desc')
                ->paginate(config('app.site_setting.list_rows'), false, [
                    'query' => $map['conditions']
                ]);

        $this->assign([
            'list'         => $list,
            'keyword'      => $map['conditions']['keyword'],
            'search_field' => $map['conditions']['search_field'],
            'title'        => '栏目列表'
        ]);
        return $this->fetch();
    }

    /**
     * 栏目树状结构
     */
    public function tree()
    {
        if ($this->request->isPost()) {
		    $data     = $this->request->post();
            $templist = [];
			if ($data) foreach($data as $k => $v) {
                if (strpos($k, 'sort-') === false) continue;
                $temp['id']   = intval(str_replace('sort-', '', $k));
                $temp['sort'] = $v;
                $templist[] = $temp;
            }

            $ColumnModel = new ColumnModel();
            if ($ColumnModel->saveAll($templist)) {
                $this->success('排序成功', cookie('__forward__'));
            } else {
                $this->error('排序失败');
            }
        } else {
            cookie('__forward__', $_SERVER['REQUEST_URI']);
            $list = ColumnModel::where(['status' => 1])
                    ->field('id,pid,title,en_title,route_name,sort,status,model_id')
                    ->order('id asc,sort asc')
                    ->select();
            $list = $list ? object_to_array($list) : null;
            $list = Tree::toFormatTree($list);
            
            $this->assign([
                'list'         => $list,
                'keyword'      => '',
                'search_field' => '',
                'title'        => '栏目树状结构'
            ]);
            return $this->fetch();
        }
    }
	
	/**
	 * 新增
	 */
	public function add()
	{
	    if ($this->request->isPost()) {
		    $data   = $this->request->post();
			
			// 验证
            $result = $this->validate($data, 'Column');
            if (true !== $result) $this->error($result);
			
			if (ColumnModel::create($data)) {
                return $this->success('新增成功', url('index'));
            } else {
                return $this->error('新增失败');
            }
		} else {
            $models  = DataModelModel::where(['status' => 1])->field('id,title')->select();
            $columns = ColumnModel::queryOneOrList(['status' => 1], 'id,title,pid', 'list', 'id asc');
            $columns = $columns ? Tree::toFormatTree($columns) : [];
            $columns = array_merge(array(0 => array('id' => 0, 'title_show' => '顶级栏目')), $columns);

			$this->assign([
			    'models'  => $models,
			    'columns' => $columns,
				'title'   => '新增栏目'
			]);
			return $this->fetch();
		}
	}
	
	/**
	 * 编辑
	 */
	public function edit()
	{
		$id = input('id/d');
    	if ($id <= 0 || !is_numeric($id)) $this->error('参数错误');
	    if ($this->request->isPost()) {
		    $data   = $this->request->post();
			
			// 验证
            $result = $this->validate($data, 'Column');
            if (true !== $result) $this->error($result);

            if (ColumnModel::update($data)) {
                $this->success('编辑成功', url('index'));
            } else {
                $this->error('编辑失败');
            }
		} else {
			$info    = ColumnModel::get($id);

            $models  = DataModelModel::where(['status' => 1])->field('id,title')->select();
            $columns = ColumnModel::queryOneOrList(['status' => 1], 'id,title,pid', 'list', 'id asc');
            $columns = $columns ? Tree::toFormatTree($columns) : [];
            $columns = array_merge(array(0 => array('id' => 0, 'title_show' => '顶级栏目')), $columns);

			$this->assign([
				'info'    => $info,
			    'models'  => $models,
			    'columns' => $columns,
				'title'   => '编辑栏目'
			]);
			return $this->fetch();
		}
	}
	
	/**
	 * 删除
	 */
	public function delete($ids = 0)
	{
        (int) $ids || $this->error('参数错误');
        $map  = ['id' => $ids];

		$flag = ColumnModel::where(['id' => $ids])->delete();
        return $flag ? $this->success('删除成功!') : $this->error('删除失败!');
	}
	
	/**
	 * 禁用/启用
	 * @param array $ids id数组
     * @param integer $status 状态值
     */
    public function setStatus($ids = [], $status)
    {
        empty($ids) && $this->error('请选择要操作的数据');
        !is_numeric((int) $status) && $this->error('参数错误');
        
        $map  = ['id' => $ids];
        $info = ColumnModel::where($map)->setField('status', $status);
        $tips = $status == 1 ? '启用' : '禁用';
        return $info !== FALSE ? $this->success($tips.'成功') : $this->error($tips.'失败');
    }
}